import { useEffect, useState } from "react";
import { throttle } from "underscore";

export default function useScrollPosition() {
    const [scrollX, setScrollX] = useState(0)
    const [scrollY, setScrollY] = useState(0)
    useEffect(() => {
        // 节流 防止频繁执行滚动回掉 一直调用组件函数 虽然diff会判断不需要渲染
        const scrollPositionHandler =throttle(function(){
            setScrollX(window.screenX)
            setScrollY(window.scrollY)
        }, 100)
        // 监听鼠标滚动事件
        window.addEventListener('scroll', scrollPositionHandler)
        return () => window.removeEventListener('scroll', scrollPositionHandler)
    },[])
    return {scrollX, scrollY}
}